const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const logger = require('../utils/logger');

/**
 * 阿里云短信服务
 */
class SmsService {
  constructor() {
    this.config = {
      accessKeyId: process.env.SMS_ACCESS_KEY_ID,
      accessKeySecret: process.env.SMS_ACCESS_KEY_SECRET,
      endpoint: 'dysmsapi.aliyuncs.com'
    };
    
    // 检查配置
    if (!this.config.accessKeyId || !this.config.accessKeySecret) {
      logger.warn('阿里云短信服务未配置，将使用模拟模式');
      this.mockMode = true;
    } else {
      this.client = this.createClient();
      this.mockMode = false;
      logger.info('阿里云短信服务初始化成功');
    }
  }

  createClient() {
    const config = new OpenApi.Config({
      accessKeyId: this.config.accessKeyId,
      accessKeySecret: this.config.accessKeySecret,
    });
    config.endpoint = this.config.endpoint;
    return new Dysmsapi20170525.default(config);
  }

  /**
   * 发送短信
   * @param {Object} params - 短信参数
   * @param {string} params.phoneNumbers - 手机号
   * @param {string} params.signName - 短信签名
   * @param {string} params.templateCode - 短信模板CODE
   * @param {Object|string} params.templateParam - 模板参数
   */
  async sendSms(params) {
    if (!params.phoneNumbers) {
      throw new Error('手机号码不能为空');
    }
    if (!params.signName) {
      throw new Error('短信签名不能为空');
    }
    if (!params.templateCode) {
      throw new Error('短信模板CODE不能为空');
    }

    // 模拟模式
    if (this.mockMode) {
      logger.info('[模拟模式] 短信发送', {
        phone: params.phoneNumbers,
        signName: params.signName,
        templateCode: params.templateCode,
        templateParam: params.templateParam
      });
      return {
        success: true,
        data: {
          Code: 'OK',
          Message: '模拟发送成功',
          RequestId: 'MOCK-' + Date.now()
        },
        message: '短信发送成功（模拟模式）'
      };
    }

    // 真实发送
    let templateParam = params.templateParam;
    if (typeof templateParam === 'object') {
      templateParam = JSON.stringify(templateParam);
    }

    const sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: params.phoneNumbers,
      signName: params.signName,
      templateCode: params.templateCode,
      templateParam: templateParam
    });

    const runtime = new Util.RuntimeOptions({});

    try {
      const response = await this.client.sendSmsWithOptions(sendSmsRequest, runtime);
      
      logger.info('短信发送成功', {
        phone: params.phoneNumbers,
        requestId: response.body.RequestId,
        code: response.body.Code
      });
      
      return {
        success: true,
        data: response.body,
        message: '短信发送成功'
      };
    } catch (error) {
      logger.error('短信发送失败', {
        phone: params.phoneNumbers,
        error: error.message,
        code: error.code
      });
      
      return {
        success: false,
        message: error.message,
        recommend: error.data ? error.data["Recommend"] : null,
        error: error
      };
    }
  }

  /**
   * 发送验证码
   * @param {string} phoneNumber - 手机号
   * @param {string} code - 验证码
   * @param {string} signName - 短信签名
   * @param {string} templateCode - 短信模板CODE
   */
  async sendVerificationCode(phoneNumber, code, signName, templateCode) {
    return this.sendSms({
      phoneNumbers: phoneNumber,
      signName: signName || process.env.SMS_SIGN_NAME,
      templateCode: templateCode || process.env.SMS_TEMPLATE_CODE,
      templateParam: { code }
    });
  }
}

// 创建全局实例
const smsService = new SmsService();

module.exports = smsService;

